package com.cljh.service.impl;

import com.cljh.bean.Admin;
import com.cljh.bean.Saler;
import com.cljh.controller.page.AdminSaler;
import com.cljh.controller.page.PageBean;
import com.cljh.mapper.AdminMapper;
import com.cljh.mapper.SalerMapper;
import com.cljh.service.SalerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SalerServiceImpl implements SalerService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    SalerMapper salerMapper;
    @Transactional
    @Override
    public boolean save(AdminSaler adminSaler) {
        Admin admin = new Admin();
        Saler saler = new Saler();
        admin.setUsername(adminSaler.getUsername());
        admin.setPassword(adminSaler.getPassword());
        admin.setNickname(adminSaler.getNickname());
        admin.setPhone(adminSaler.getPhone());
        admin.setGender(adminSaler.getGender());
        admin.setAddress(adminSaler.getAddress());
        saler.setIdCard(adminSaler.getIdCard());
        saler.setBirthday(adminSaler.getBirthday());
        if (adminSaler.getCompany()!=null){
            saler.setCompany(adminSaler.getCompany());
        }
        if (adminSaler.getPosition()!=null){
            saler.setPosition(adminSaler.getPosition());
        }
        if (adminSaler.getAchieve()!=null){
            saler.setAchieve(adminSaler.getAchieve());
        }
        if (adminSaler.getDepartment()!=null){
            saler.setDepartment(adminSaler.getDepartment());
        }
        int save = adminMapper.save(admin);
        Integer id = admin.getId();
        saler.setAdminId(id);
        int save1 = salerMapper.save(saler);


        return save>0&&save1>0;
    }

    @Override
    public PageBean<Saler> selectAllByCondition(Integer currentPage, Integer pageSize, Admin admin) {
        //计算开始索引
        int begin = (currentPage - 1) * pageSize;

        String first = admin.getUsername();
        if (first!=null&&first.length()>0){
            admin.setUsername("%"+first+"%");
        }

        System.out.println(admin.getUsername());
//        List<Admin> admins = adminMapper.selectAllByCondition(begin, pageSize, admin);
//        int i = adminMapper.selectCount(admin);
        List<Saler> salers = salerMapper.selectAllByCondition(begin, pageSize, admin);
        int i = salerMapper.selectCount(admin);
        PageBean<Saler> adminPageBean = new PageBean<>();
        adminPageBean.setRows(salers);
        adminPageBean.setTotalCount(i);
        return adminPageBean;
    }

    @Override
    public Saler selectByAdminId(Integer id) {
        return salerMapper.selectByAdminId(id);
    }

    @Override
    public boolean upd(Saler saler) {
        return salerMapper.upd(saler)>0;
    }
}
